import React, { useState, useEffect } from 'react';
import {
  Table,
  Input,
  Button,
  Space,
  Pagination,
  Row,
  Col,
  Dialog,
  MessagePlugin
} from 'tdesign-react';

import styles from './index.module.less';
import { getCustomerList, getCustomerDetail, deleteCustomer, updateCustomer, updateCustomerBalance, createCustomer } from 'services/customer';

interface Customer {
  id: string;
  company_name: string;
  invite_code: string;
  admin_name: string;
  admin_phone: string;
  company_account_balance: number;
  created_at: string;
}

const CustomerList: React.FC = () => {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState({
    companyName: '',
    adminName: '',
    adminPhone: ''
  });
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0
  });

  // 编辑弹窗相关状态
  const [editDialogVisible, setEditDialogVisible] = useState(false);
  const [editingCustomer, setEditingCustomer] = useState<Customer | null>(null);
  const [editForm, setEditForm] = useState({
    company_name: '',
    invite_code: '',
    admin_name: '',
    admin_phone: '',
    company_account_balance: 0
  });

  // 删除弹窗相关状态
  const [deleteDialogVisible, setDeleteDialogVisible] = useState(false);
  const [deletingCustomer, setDeletingCustomer] = useState<Customer | null>(null);

  // 新增弹窗相关状态
  const [createDialogVisible, setCreateDialogVisible] = useState(false);
  const [createForm, setCreateForm] = useState({
    company_name: '',
    admin_name: '',
    admin_phone: '',
    admin_password: ''
  });

  // 组装组合搜索：企业名 + 姓名 + 手机号（用空格拼接，后端按空格拆分进行多关键词匹配）
  const buildSearch = () => {
    const parts = [searchParams.companyName, searchParams.adminName, searchParams.adminPhone]
      .map((s) => (s || '').trim())
      .filter(Boolean);
    return parts.join(' ');
  };

  const fetchCustomers = async (page?: number, pageSize?: number, searchOverride?: string) => {
    setLoading(true);
    try {
      const { current, pageSize: size } = pagination;
      const params = {
        page: page ?? current,
        page_size: pageSize ?? size,
        search: searchOverride !== undefined ? searchOverride : buildSearch(),
        sort_by: 'created_at' as const,
        sort_order: 'desc' as const,
      };
      const res = await getCustomerList(params);
      // 兼容两种返回：
      // 1) { code, msg, data: { items, total, page, page_size } }
      // 2) { items, total, page, page_size }
      const payload: any = (res as any)?.data ?? (res as any);
      const items = payload?.items ?? payload?.list ?? [];
      const total = payload?.total ?? 0;
      // 调试输出，便于排查字段不一致问题
      // eslint-disable-next-line no-console
      console.log('CustomerList payload:', payload);
      setCustomers(items as unknown as Customer[]);
      setPagination((prev) => ({ ...prev, total, current: params.page, pageSize: params.page_size }));
    } catch (e: any) {
      MessagePlugin.error(e?.message || '获取客户列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCustomers(1, pagination.pageSize);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const columns = [
    {
      title: '序号',
      colKey: 'index',
      width: 80,
      cell: ({ rowIndex }: any) => (pagination.current - 1) * pagination.pageSize + rowIndex + 1
    },
    {
      title: '客户公司名称',
      colKey: 'company_name',
      width: 200
    },
    {
      title: '客户公司ID',
      colKey: 'id',
      width: 120
    },
    {
      title: '管理员姓名',
      colKey: 'admin_name',
      width: 120
    },
    {
      title: '联系电话',
      colKey: 'admin_phone',
      width: 140
    },
    {
      title: '企业邀请码',
      colKey: 'invite_code',
      width: 120
    },
    {
      title: '账户余额（元）',
      colKey: 'company_account_balance',
      width: 140,
      cell: ({ row }: any) => {
        const balance = row.company_account_balance / 100; // 分转元
        return (
          <span style={{ color: balance === 0 ? '#e34d59' : '#000' }}>
            {balance.toFixed(2)}
          </span>
        );
      }
    },
    {
      title: '操作',
      colKey: 'operation',
      width: 120,
      fixed: 'right' as const,
      cell: ({ row }: any) => (
        <Space>
          <Button
            theme="primary"
            variant="text"
            size="small"
            onClick={() => handleEdit(row)}
          >
            编辑
          </Button>
          <Button
            theme="danger"
            variant="text"
            size="small"
            onClick={() => handleDelete(row)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  const handleSearch = () => {
    // 搜索重置到第 1 页
    setPagination((prev) => ({ ...prev, current: 1 }));
    fetchCustomers(1, pagination.pageSize, buildSearch());
  };

  const handleReset = () => {
    setSearchParams({
      companyName: '',
      adminName: '',
      adminPhone: ''
    });
    // 重置后刷新列表到第一页，清空 search 传参
    setPagination((prev) => ({ ...prev, current: 1 }));
    fetchCustomers(1, pagination.pageSize, '');
  };

  // 新增弹窗：打开/取消/保存
  const handleCreateOpen = () => {
    setCreateDialogVisible(true);
  };

  const handleCreateCancel = () => {
    setCreateDialogVisible(false);
    setCreateForm({ company_name: '', admin_name: '', admin_phone: '', admin_password: '' });
  };

  const handleCreateFormChange = (field: keyof typeof createForm, value: string) => {
    setCreateForm(prev => ({ ...prev, [field]: value }));
  };

  const handleCreateSave = async () => {
    try {
      // 前置校验：公司名/管理员姓名(1-100)、手机号(11位 1[3-9]开头)、密码(6-100)
      const name = (createForm.admin_name || '').trim();
      const company = (createForm.company_name || '').trim();
      const phone = (createForm.admin_phone || '').trim();
      const pwd = createForm.admin_password || '';
      const phoneReg = /^1[3-9]\d{9}$/;

      if (!company || company.length < 1 || company.length > 100) {
        MessagePlugin.warning('企业名称必填，长度需在1-100个字符内');
        return;
      }
      if (!name || name.length < 1 || name.length > 100) {
        MessagePlugin.warning('管理员姓名必填，长度需在1-100个字符内');
        return;
      }
      if (!phoneReg.test(phone)) {
        MessagePlugin.warning('手机号格式不合法，需为以1开头的11位数字，第二位3-9');
        return;
      }
      if (!pwd || pwd.length < 6 || pwd.length > 100) {
        MessagePlugin.warning('管理员密码必填，长度应在6-100个字符');
        return;
      }
      setLoading(true);
      const createRes = await createCustomer({
        company_name: company,
        admin_name: name,
        admin_phone: phone,
        admin_password: pwd,
        operator_type: 'PLATFORM',
        // 预警设置：余额阈值=10，预警电话=管理员电话，默认不启用
        company_account_balance_warning_phone: phone,
        company_account_balance_warning_enable: false,
        company_account_balance_warning_val: 10,
      });
      // 提取新客户ID，兼容两种返回结构
      const createdPayload: any = (createRes as any)?.data ?? (createRes as any);
      const newId: string | undefined = createdPayload?.data?.id ?? createdPayload?.id;
      // 创建完成后，初始化余额为 20 元（2000 分）
      if (newId) {
        await updateCustomerBalance(newId, {
          amount: 2000,
          operation: 'add',
          remark: '初始化余额20元'
        });
      }
      MessagePlugin.success('客户创建成功');
      setCreateDialogVisible(false);
      setCreateForm({ company_name: '', admin_name: '', admin_phone: '', admin_password: '' });
      await fetchCustomers(1, pagination.pageSize);
      setPagination(prev => ({ ...prev, current: 1 }));
    } catch (e: any) {
      MessagePlugin.error(e?.message || '客户创建失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearchParamChange = (field: keyof typeof searchParams, value: string) => {
    setSearchParams(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleEdit = async (customer: Customer) => {
    try {
      setLoading(true);
      // 表格中的“客户公司ID”就是后端的 id
      const res = await getCustomerDetail(customer.id);
      const detail: any = (res as any)?.data ?? (res as any);
      setEditingCustomer(detail as Customer);
      setEditForm({
        company_name: detail.company_name || '',
        invite_code: detail.invite_code || '',
        admin_name: detail.admin_name || '',
        admin_phone: detail.admin_phone || '',
        company_account_balance: (detail.company_account_balance ?? 0) / 100, // 分转元
      });
      setEditDialogVisible(true);
    } catch (e: any) {
      MessagePlugin.error(e?.message || '获取客户详情失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = (customer: Customer) => {
    setDeletingCustomer(customer);
    setDeleteDialogVisible(true);
  };

  const handleDeleteConfirm = async () => {
    if (!deletingCustomer) return;
    try {
      setLoading(true);
      const res = await deleteCustomer(deletingCustomer.id);
      MessagePlugin.success((res as any)?.msg || '客户删除成功');
      setDeleteDialogVisible(false);
      setDeletingCustomer(null);
      await fetchCustomers();
    } catch (e: any) {
      MessagePlugin.error(e?.message || '删除客户失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteCancel = () => {
    setDeleteDialogVisible(false);
    setDeletingCustomer(null);
  };

  const handleEditFormChange = (field: string, value: string | number) => {
    setEditForm(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleEditSave = async () => {
    if (!editingCustomer) return;
    try {
      setLoading(true);
      // 1) 基础信息更新（不包含余额本体）
      await updateCustomer(editingCustomer.id, {
        company_name: editForm.company_name,
        admin_name: editForm.admin_name,
        admin_phone: editForm.admin_phone,
        // 预警相关字段暂不在表单中，后续如需支持可在此补充
      });

      // 2) 若余额有变化，调用余额接口（单位：分）
      const oldCents = editingCustomer.company_account_balance; // 已是分
      const newCents = Math.round((editForm.company_account_balance || 0) * 100);
      const diff = newCents - oldCents;
      if (diff !== 0) {
        await updateCustomerBalance(editingCustomer.id, {
          amount: Math.abs(diff),
          operation: diff > 0 ? 'add' : 'subtract',
          remark: '编辑保存调整余额'
        });
      }

      MessagePlugin.success('保存成功');
      setEditDialogVisible(false);
      setEditingCustomer(null);
      await fetchCustomers();
    } catch (e: any) {
      MessagePlugin.error(e?.message || '保存失败');
    } finally {
      setLoading(false);
    }
  };

  const handleEditCancel = () => {
    setEditDialogVisible(false);
    setEditingCustomer(null);
    setEditForm({
      company_name: '',
      invite_code: '',
      admin_name: '',
      admin_phone: '',
      company_account_balance: 0
    });
  };

  const handlePageChange = (pageInfo: any) => {
    setPagination((prev) => ({ ...prev, current: pageInfo.current, pageSize: pageInfo.pageSize }));
    fetchCustomers(pageInfo.current, pageInfo.pageSize);
  };

  return (
    <div className={styles.container}>
      {/* 搜索区域 */}
      <Row style={{ marginBottom: 16 }}>
        <Col span={24}>
          <Space size="large">
            <Space>
              <span>企业名称</span>
              <Input
                value={searchParams.companyName}
                onChange={(value) => handleSearchParamChange('companyName', value)}
                placeholder="请输入企业名称"
                style={{ width: 200 }}
                onEnter={handleSearch}
              />
            </Space>
            <Space>
              <span>联系人姓名</span>
              <Input
                value={searchParams.adminName}
                onChange={(value) => handleSearchParamChange('adminName', value)}
                placeholder="请输入联系人姓名"
                style={{ width: 200 }}
                onEnter={handleSearch}
              />
            </Space>
            <Space>
              <span>手机号</span>
              <Input
                value={searchParams.adminPhone}
                onChange={(value) => handleSearchParamChange('adminPhone', value)}
                placeholder="请输入手机号"
                style={{ width: 200 }}
                onEnter={handleSearch}
              />
            </Space>
            <Button theme="primary" onClick={handleSearch}>
              查询
            </Button>
            <Button variant="outline" onClick={handleReset}>
              重置
            </Button>
            <Button theme="primary" variant="outline" onClick={handleCreateOpen}>
              新增客户
            </Button>
          </Space>
        </Col>
      </Row>

      {/* 表格 */}
      <Table
        data={customers}
        columns={columns}
        loading={loading}
        rowKey="id"
        bordered
        hover
        size="medium"
      />

      {/* 分页 */}
      <div style={{ marginTop: 16, textAlign: 'right' }}>
        <Pagination
          current={pagination.current}
          pageSize={pagination.pageSize}
          total={pagination.total}
          showJumper
          onChange={handlePageChange}
        />
        <div style={{ marginTop: 8, fontSize: '12px', color: '#666' }}>
          共 {pagination.total} 条数据
        </div>
      </div>

      {/* 编辑弹窗 */}
      <Dialog
        visible={editDialogVisible}
        header="编辑"
        width={800}
        onClose={handleEditCancel}
        onConfirm={handleEditSave}
        confirmBtn="确认"
        cancelBtn="取消"
      >
        <div style={{ padding: '24px', display: 'flex', gap: '40px' }}>
          {/* 左列 */}
          <div style={{ flex: 1 }}>
            <div style={{ marginBottom: 20 }}>
              <div style={{ marginBottom: 8, fontSize: '14px', color: '#333', fontWeight: 500 }}>
                企业名称
              </div>
              <Input
                value={editForm.company_name}
                onChange={(value) => handleEditFormChange('company_name', value)}
                placeholder="广州市某某某某有限公司"
                style={{ width: '100%' }}
              />
            </div>

            <div style={{ marginBottom: 20 }}>
              <div style={{ marginBottom: 8, fontSize: '14px', color: '#333', fontWeight: 500 }}>
                管理员姓名
              </div>
              <Input
                value={editForm.admin_name}
                onChange={(value) => handleEditFormChange('admin_name', value)}
                placeholder="张三"
                style={{ width: '100%' }}
              />
            </div>

            <div style={{ marginBottom: 20 }}>
              <div style={{ marginBottom: 8, fontSize: '14px', color: '#333', fontWeight: 500 }}>
                企业邀请码
              </div>
              <Input
                value={editForm.invite_code}
                onChange={(value) => handleEditFormChange('invite_code', value)}
                placeholder="RYJJJBQM"
                style={{ width: '100%' }}
              />
            </div>
          </div>

          {/* 右列 */}
          <div style={{ flex: 1 }}>
            <div style={{ marginBottom: 20 }}>
              <div style={{ marginBottom: 8, fontSize: '14px', color: '#333', fontWeight: 500 }}>
                企业ID
              </div>
              <Input
                value={editForm.invite_code}
                onChange={(value) => handleEditFormChange('invite_code', value)}
                placeholder="RYJJJBQM"
                style={{ width: '100%' }}
              />
            </div>

            <div style={{ marginBottom: 20 }}>
              <div style={{ marginBottom: 8, fontSize: '14px', color: '#333', fontWeight: 500 }}>
                联系电话
              </div>
              <Input
                value={editForm.admin_phone}
                onChange={(value) => handleEditFormChange('admin_phone', value)}
                placeholder="19865305951"
                style={{ width: '100%' }}
              />
            </div>

            <div style={{ marginBottom: 20 }}>
              <div style={{ marginBottom: 8, fontSize: '14px', color: '#333', fontWeight: 500 }}>
                *账户余额
              </div>
              <Input
                value={editForm.company_account_balance.toString()}
                onChange={(value) => handleEditFormChange('company_account_balance', parseFloat(value) || 0)}
                placeholder="请输入当前账户余额"
                style={{ width: '100%' }}
              />
            </div>
          </div>
        </div>
      </Dialog>

      {/* 新增客户弹窗 */}
      <Dialog
        visible={createDialogVisible}
        header="新增客户"
        width={600}
        onClose={handleCreateCancel}
        onConfirm={handleCreateSave}
        confirmBtn="创建"
        cancelBtn="取消"
      >
        <div style={{ padding: '24px' }}>
          <div style={{ marginBottom: 16 }}>
            <div style={{ marginBottom: 8, fontSize: '14px', color: '#333', fontWeight: 500 }}>企业名称</div>
            <Input
              value={createForm.company_name}
              onChange={(v) => handleCreateFormChange('company_name', v)}
              placeholder="北京科技有限公司"
            />
          </div>
          <div style={{ marginBottom: 16 }}>
            <div style={{ marginBottom: 8, fontSize: '14px', color: '#333', fontWeight: 500 }}>管理员姓名</div>
            <Input
              value={createForm.admin_name}
              onChange={(v) => handleCreateFormChange('admin_name', v)}
              placeholder="张三"
            />
          </div>
          <div style={{ marginBottom: 16 }}>
            <div style={{ marginBottom: 8, fontSize: '14px', color: '#333', fontWeight: 500 }}>联系电话</div>
            <Input
              value={createForm.admin_phone}
              onChange={(v) => handleCreateFormChange('admin_phone', v)}
              placeholder="13800138000"
            />
          </div>
          <div style={{ marginBottom: 16 }}>
            <div style={{ marginBottom: 8, fontSize: '14px', color: '#333', fontWeight: 500 }}>管理员密码</div>
            <Input
              value={createForm.admin_password}
              onChange={(v) => handleCreateFormChange('admin_password', v)}
              type="password"
              placeholder="password123"
            />
          </div>
        </div>
      </Dialog>

      {/* 删除确认弹窗 */}
      <Dialog
        visible={deleteDialogVisible}
        header="删除"
        width={400}
        onClose={handleDeleteCancel}
        onConfirm={handleDeleteConfirm}
        confirmBtn="确认删除"
        cancelBtn="取消"
      >
        <div style={{ padding: '20px 0', textAlign: 'center' }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            marginBottom: 16
          }}>
            <div style={{
              width: 20,
              height: 20,
              borderRadius: '50%',
              backgroundColor: '#0052d9',
              color: 'white',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '12px',
              fontWeight: 'bold',
              marginRight: 8
            }}>
              !
            </div>
            <span style={{ fontSize: '16px', fontWeight: 500 }}>删除</span>
          </div>
          <div style={{ fontSize: '14px', color: '#666' }}>
            是否确认删除？
          </div>
        </div>
      </Dialog>
    </div>
  );
};

export default CustomerList;
